//
//  ViewController.m
//  HongxuanBluetooth
//
//  Created by 广州弘轩科技发展有限公司 on 2023/7/27.
//

#import "ViewController.h"
#import "Masonry.h"
#import "AdView.h"
@interface ViewController ()<SDCycleScrollViewDelegate>
@property (strong, nonatomic) UIButton *ConnectBt;

@property (nonatomic,strong)NSMutableArray *myDevices;


@property (nonatomic,strong)UIImageView *clickLinkageToStartview;
@property (nonatomic,strong)UIImageView *readytolinksview;
@property (nonatomic,strong)UIImageView *statebj;
@property (nonatomic,strong)UIImageView *mainscreen;
@property (nonatomic,assign)NSInteger index;
@property (strong,nonatomic) NSString *disconnectDevice;
@property (nonatomic,assign) BOOL isgai;
@property (nonatomic,assign) BOOL isopen;
@property (nonatomic,assign)NSInteger height;

@property (strong, nonatomic) BlueToothManager *blueToothManager;//蓝牙
@end

@implementation ViewController
{
    SDCycleScrollView *devicelinkScrollView;
    NSArray *_imagesURLStrings;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor blackColor];
    self.fd_prefersNavigationBarHidden = YES;
    NSLog(@"dataArr :%@",self.dataArr);
    NSLog(@"self.lbdataarray.count :%ld",self.lbdataarray.count);
    NSLog(@"ViewController self.lbdataarray :%@",self.lbdataarray);
    NSLog(@"ViewController self.bluetoothddataArray :%@",self.bluetoothddataArray);
    self.height = 0;
    if(winHeight<=736){
        self.height = 560;
    }else{
        self.height = 590;
    }
    self.index = 0;
    self.blueToothManager = [BlueToothManager shareInstance];
    self.blueToothManager.autoConnect = YES;
    [self.blueToothManager StartScan];
    [self obtainElectricity];
    [self huoqushijian];
//    先加载连接设备
    [self loadMyDevices];
    [self modeselection];
//  单人：solodemo  助手：helprdemo
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(solojump) name:@"solodemo" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(helprjump) name:@"helprdemo" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(detailjump:) name:@"detaildemo" object:nil];
//    tutoriademo
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(tutoriajump) name:@"tutoriademo" object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changelanguages) name:@"changelanguages" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textViewname:) name:@"textViewname" object:nil];
//    [[NSNotificationCenter defaultCenter]postNotificationName:@"@"disconnectDevice"" object:nil userInfo:@{@"@"uuid"":uuid}];
//    bluetoothDisconnect
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(bluetoothDisconnect:) name:@"bluetoothDisconnect" object:nil];
//    linkSuccess
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(linkSuccess:) name:@"linkSuccess" object:nil];
    
}


- (void)loadMyDevices {

//    NSMutableArray*_myDevices ;
    
    if (!_myDevices) {
        NSData *data = [[NSUserDefaults standardUserDefaults] objectForKey:@"MyDevices"];
        if (!data) {
            data = [NSData data];
        }
        _myDevices = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        if (!_myDevices) {
            _myDevices = [NSMutableArray array];
        }
        NSLog(@"首页设备设备：%@", _myDevices);
    }
}

- (void)changelanguages{
    
    if([themeColors isEqualToString:@"default"]){
        self.clickLinkageToStartview.image = [UIImage imageNamed:@"clickLinkageToStart"];
        devicelinkScrollView.backgroundColor = [UIColor blackColor];
        self.statebj.backgroundColor = [UIColor blackColor];
        self.mainscreen.image = [UIImage imageNamed:@"mainscreen"];
    }else{
        self.clickLinkageToStartview.image = [UIImage imageNamed:@"clickLinkageToStartmid"];
        devicelinkScrollView.backgroundColor = midnightRGB;
        self.statebj.backgroundColor = midnightRGB;
        self.mainscreen.image = [UIImage imageNamed:@"mianmidnight"];
        
    }
   
}
-(void)modeselection{
//    CGRectMake(50, self.view.bounds.size.height/3-50, self.view.bounds.size.width-100, self.view.bounds.size.height/3);
//    UIImageView *modeselectbj = [[UIImageView alloc] initWithFrame:CGRectMake(50, 64+20, self.view.bounds.size.width-100, 120)];
//    mianmidnight
    NSLog(@"themeColors :%@",themeColors);
    UIImageView *tabr = [[UIImageView alloc] initWithFrame:CGRectMake(0, kNavHeight-44, winWidth, 44)];
//    tabr.backgroundColor = [UIColor yellowColor];
    NSLog(@"winHeight:%f winWidth:%f",winHeight,winWidth);
    [self.view addSubview:tabr];
    UIImageView *mainscreen = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, winWidth, 44)];
    self.mainscreen = mainscreen;
    if([themeColors isEqualToString:@"default"]){
        mainscreen.image = [UIImage imageNamed:@"mainscreen"];
    }else{
        mainscreen.image = [UIImage imageNamed:@"mianmidnight"];
    }
    
    [tabr addSubview:mainscreen];
#pragma mark - 设备断开
    WeakSelf
    self.blueToothManager.ConnectionFailureBlock = ^(NSString * _Nonnull uuid) {
        
        NSLog(@"首页设备断开了 :%@",uuid);
        [[NSNotificationCenter defaultCenter]postNotificationName:@"bluetoothDisconnect" object:nil userInfo:@{@"uuid":uuid}];
    };
    self.blueToothManager.successfulConnectionBlock = ^(NSMutableArray * _Nonnull list) {
      
        NSLog(@"首页链接成功：%@",list);
        
        NSMutableArray *dataArr = [NSMutableArray arrayWithObject:list];
        NSLog(@"首页返回来的数据：%@",list);
        NSLog(@"self.bluetoothddataArray :%@",self.bluetoothddataArray);
        
        NSDictionary *dict = [NSDictionary dictionaryWithDictionary:dataArr[0][1]];
        NSMutableDictionary *mudic = [NSMutableDictionary dictionaryWithDictionary:dict[@"advertisementData"]];
        NSString* uuid = [NSString stringWithFormat:@"%@",dict[@"uuid"]];
        [mudic setObject:@"1" forKey:@"kCBAdvDataislink"];
    //            self.dataArr[self.dissdindex] = @[self.dataArr[self.dissdindex][0],mudic];
        NSDictionary *nutadict = @{@"uuid":uuid,@"advertisementData":mudic,@"name":dict[@"name"]};
        
    //    weakSelf.dataArr[weakSelf.dissdindex] = @[weakSelf.dataArr[weakSelf.dissdindex][0],nutadict];
        NSArray *datacopy = @[dataArr[0][0],nutadict];
        
        NSArray *lbdataarray = @[nutadict];
        
        if (self.bluetoothddataArray.count >0) {
            NSString *datauuid = [NSString stringWithFormat:@"%@",self.bluetoothddataArray[0][1][@"uuid"]];
        if([datauuid isEqualToString:uuid]){
            NSLog(@"vc包含了");
        }else{
            NSLog(@"vc没包含");
    //        [weakSelf.linkuuidarray addObject:linkuuid];
            NSLog(@"bluetoothddataArray4 %@ %@",self.bluetoothddataArray,datacopy);
            [self.bluetoothddataArray addObject:datacopy];
        }
            
        }else{
            NSLog(@"bluetoothddataArray3 %@ %@",self.bluetoothddataArray,datacopy);
            [self.bluetoothddataArray addObject:datacopy];
        }
//        [weakSelf.bluetoothddataArray addObject:datacopy];
        
        [weakSelf obtainElectricity];//获取最后的时间
        
        [weakSelf.lbdataarray addObject:nutadict];
        [weakSelf adddata];
        
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
           // 在子线程中执行需要延时的代码
           [NSThread sleepForTimeInterval:1.0]; // 休眠0.8秒钟

           dispatch_async(dispatch_get_main_queue(), ^{
              // 回到主线程中执行剩余操作

//               [weakSelf resendTime];
           });
        });
    };
    
    [self adddata];
    
//    没有链接设备
//#pragma mark -模拟
//    if(self.lbdataarray.count <= 0){
//
//        UIImageView *readytolinksview = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"readytolinks"]];
//        [self.view addSubview:readytolinksview];
//        [readytolinksview mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.width.height.mas_equalTo(190);
//            make.top.mas_equalTo(kNavHeight+120);
//            make.centerX.mas_equalTo(self.view);
//        }];
//
//        UIImageView *clickLinkageToStartview = [[UIImageView alloc] initWithFrame:CGRectMake(33, winHeight- SafeAreaBottomHeight-200, winWidth-66, 100)];
//        self.clickLinkageToStartview = clickLinkageToStartview;
//        if([themeColors isEqualToString:@"default"]){
//            clickLinkageToStartview.image = [UIImage imageNamed:@"clickLinkageToStart"];
//        }else{
//            clickLinkageToStartview.image = [UIImage imageNamed:@"clickLinkageToStartmid"];
//        }
////        clickLinkageToStartview.image = [UIImage imageNamed:@"clickLinkageToStart"];
//        [self.view addSubview:clickLinkageToStartview];
//    }else{
////        有设备链接
//
////        _imagesURLStrings = imagesURLStrings;
//
////        NSMutableArray *imageNames = [@[@"linkbackground",@"linkbackground"]];
//        NSMutableArray *imageNames = [[NSMutableArray alloc] init];
//        _imagesURLStrings = imageNames;
////        lbdataarray
//        for (int i = 0; i<self.lbdataarray.count; i++) {
//            [imageNames addObject:@"linkbackground"];
//        }
//
//        // 本地加载 --- 创建不带标题的图片轮播器
////        devicelinkScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(30, kNavHeight+10, winWidth-60, 590) shouldInfiniteLoop:NO imageNamesGroup:imageNames];
////        devicelinkScrollView.delegate = self;
////        devicelinkScrollView.pageControlStyle = SDCycleScrollViewPageContolStyleAnimated;
////        devicelinkScrollView.scrollDirection = UICollectionViewScrollDirectionVertical;
//        //         --- 轮播时间间隔，默认1.0秒，可自定义
//        //cycleScrollView.autoScrollTimeInterval = 4.0;
//
//        devicelinkScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(30, kNavHeight+10, winWidth-60, self.height) delegate:self placeholderImage:nil];
//        devicelinkScrollView.imageURLStringsGroup = _imagesURLStrings ;
//        devicelinkScrollView.autoScroll = NO;
//        if([themeColors isEqualToString:@"default"]){
//            devicelinkScrollView.backgroundColor = [UIColor blackColor];
//        }else{
//            devicelinkScrollView.backgroundColor = midnightRGB;
//        }
//        [self.view addSubview:devicelinkScrollView];
//    }
    
    
    UIImageView *statebj = [[UIImageView alloc] init];
    self.statebj = statebj;
    if([themeColors isEqualToString:@"default"]){
        statebj.backgroundColor = [UIColor blackColor];
    }else{
        statebj.backgroundColor = midnightRGB;
    }
    [self.view addSubview:statebj];
    [statebj mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.left.mas_equalTo(0);
        make.bottom.mas_equalTo(-SafeAreaBottomHeight-34);
        make.height.mas_equalTo(50);
    }];
    
#pragma mark 设置入口
    UIImageView *optionview = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"option"]];
    optionview.userInteractionEnabled = YES;
    [self.view addSubview:optionview];
    [optionview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(-SafeAreaBottomHeight-37);
        make.width.mas_equalTo(48);
        make.height.mas_equalTo(43);
        make.left.mas_equalTo(26);
    }];
    
    UIButton *optionbt = [UIButton buttonWithType:UIButtonTypeCustom];
    [optionbt addTarget:self action:@selector(JumpOption) forControlEvents:UIControlEventTouchUpInside];
    [optionview addSubview:optionbt];
    [optionbt mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(optionview);
    }];
    
    
#pragma mark 链接入口
    UIImageView *linkageview = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"linkage"]];
    linkageview.userInteractionEnabled = YES;
    [self.view addSubview:linkageview];
    [linkageview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(-SafeAreaBottomHeight-37);
        make.width.mas_equalTo(55);
        make.height.mas_equalTo(43);
        make.right.mas_equalTo(-26);
    }];
    
    UIButton *linkagebt = [UIButton buttonWithType:UIButtonTypeCustom];
    [linkagebt addTarget:self action:@selector(JumpLinke) forControlEvents:UIControlEventTouchUpInside];
    [linkageview addSubview:linkagebt];
    [linkagebt mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(linkageview);
    }];
    
    
    UIImageView *bluetherview = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"bluether"]];
    bluetherview.userInteractionEnabled = YES;
    [self.view addSubview:bluetherview];
    [bluetherview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view);
        make.bottom.mas_equalTo(-SafeAreaBottomHeight-52);
        make.height.mas_equalTo(13);
    }];
    
}
#pragma mark - 获取时间
-(void)obtainElectricity{

    //    获取最后的时间
    Byte send[] = {0x58,0x57,0x03,0x0B,0x00,0x00,0x00,0x01};
    NSData *sendData = [NSData dataWithBytes:&send length:sizeof(send)];
    [self.blueToothManager writeData:sendData];
    
    NSLog(@"获取最后的时间blueToothManager: %@",self.blueToothManager);
    //    链接
//    self.blueToothManager.datastrBlock = ^(NSString * _Nonnull datastr) {
//        NSLog(@"获取最后的时间： %@",datastr);
//    };
    self.blueToothManager.datalasttimeBlock = ^(NSString * _Nonnull lasttime) {
        NSLog(@"获取最后的时间： %@",lasttime);
        NSArray *Arr = [NSArray array];
        Arr = [lasttime componentsSeparatedByString:@"0x585703"];
//        NSLog(@"获取最后的时间：%@",Arr);
        NSString *time = [Arr[1] substringWithRange:NSMakeRange(4, 2)];
        NSString *minute = [Arr[1] substringWithRange:NSMakeRange(6, 2)];
        
//        字节 10-字节 13:芯片唯一ID 设备号
        NSString *chipid = [Arr[1] substringWithRange:NSMakeRange(14, 6)];
        NSLog(@"\n时:%@\n分:%@\n芯片id:%@",time,minute,chipid);
        
//        int dinal = [XHbluetoolUtils hexadecimalto10:results2];
//        hexadecimalto10
        if([XHbluetoolUtils hexadecimalto10:time]<10){
            time = [NSString stringWithFormat:@"0%d",[XHbluetoolUtils hexadecimalto10:time]];
        }else{
            time = [NSString stringWithFormat:@"%d",[XHbluetoolUtils hexadecimalto10:time]];
        }
        if([XHbluetoolUtils hexadecimalto10:minute]<10){
            minute = [NSString stringWithFormat:@"0%d",[XHbluetoolUtils hexadecimalto10:minute]];
        }else{
            minute = [NSString stringWithFormat:@"%d",[XHbluetoolUtils hexadecimalto10:minute]];
        }
        
        NSString *timeshij = [NSString stringWithFormat:@"%@:%@",time,minute];
        
//        NSLog(@"存储的时间：%@",timeshij);
//        NSLog(@"%@",self.myDevices);
        //    存入蓝牙时间
        [[NSUserDefaults standardUserDefaults] setObject:timeshij forKey:@"Bluetoothtime"];
        //这里建议同步存储到磁盘中，但是不是必须的
        [[NSUserDefaults standardUserDefaults] synchronize];
    };
}
- (void)resendTime{
    
    //    存入蓝牙时间NSString *arr= [[NSUserDefaults standardUserDefaults] objectForKey:@"theme"];
    NSString *resendTime= [[NSUserDefaults standardUserDefaults] objectForKey:@"untraveledTime"];
    if(kStringIsEmpty(resendTime)||[resendTime isEqualToString:@"无"]){
        NSLog(@"显示无。");
        return;
    }
    NSLog(@"resendTime :%@",resendTime);
    NSArray *array = [resendTime componentsSeparatedByString:@":"];
    NSString * time = [NSString stringWithFormat:@"%@",array[0]];
    NSString * hour = [NSString stringWithFormat:@"%@",array[1]];
    int data = time.intValue;
    int tow = hour.intValue;
    NSLog(@"%d",data);
    data = [XHbluetoolUtils intTransitionhex16:data];
    if(data>12){
        data = data - 12;
    }
    
    NSLog(@"12进制时间：%d",data);
    tow = [XHbluetoolUtils intTransitionhex16:tow];
    Byte send[] = {0x58,0x57,0x03,0xff,0x00,data,tow,0x01};
    NSData *sendData = [NSData dataWithBytes:&send length:sizeof(send)];
//    self.isArrive = NO;//发送时no 到指定位置折为yes
    [self.blueToothManager writeData:sendData];
    
    [[NSUserDefaults standardUserDefaults] setObject:@"无" forKey:@"untraveledTime"];
    //这里建议同步存储到磁盘中，但是不是必须的
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    //    存入蓝牙时间
    [[NSUserDefaults standardUserDefaults] setObject:resendTime forKey:@"Bluetoothtime"];
    //这里建议同步存储到磁盘中，但是不是必须的
    [[NSUserDefaults standardUserDefaults] synchronize];
}
- (void)adddata{
    
//    no 时间未超过 对于伪装不显示真实，直接显示界面
//    yes 时间超过显示原有的功能
    if(!XHbluetoolUtils.beginurl){
        NSLog(@" isopen no");
        
        self.readytolinksview.hidden = YES;
        self.clickLinkageToStartview.hidden = YES;
        [self.readytolinksview removeFromSuperview];
        [self.clickLinkageToStartview removeFromSuperview];
//        有设备链接

//        _imagesURLStrings = imagesURLStrings;
       
//        NSMutableArray *imageNames = [@[@"linkbackground",@"linkbackground"]];
        NSMutableArray *imageNames = [[NSMutableArray alloc] init];
        [imageNames addObject:@"linkbackground"];
        _imagesURLStrings = imageNames;
//        lbdataarray
   
       
        
        
        devicelinkScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(30, kNavHeight+10, winWidth-60, self.height) delegate:self placeholderImage:nil];
        devicelinkScrollView.imageURLStringsGroup = _imagesURLStrings ;
        devicelinkScrollView.autoScroll = NO;
        if([themeColors isEqualToString:@"default"]){
            devicelinkScrollView.backgroundColor = [UIColor blackColor];
        }else{
            devicelinkScrollView.backgroundColor = midnightRGB;
        }
        [self.view addSubview:devicelinkScrollView];
        
        
        
    }else{
        NSLog(@" isopen yes");
    
    
#pragma mark -是否有数据显示
    if(self.lbdataarray.count <= 0){
        
        self.readytolinksview = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"readytolinks"]];
        [self.view addSubview:self.readytolinksview ];
        [self.readytolinksview  mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.height.mas_equalTo(190);
            make.top.mas_equalTo(kNavHeight+120);
            make.centerX.mas_equalTo(self.view);
        }];
        
        self.clickLinkageToStartview  = [[UIImageView alloc] initWithFrame:CGRectMake(33, winHeight- SafeAreaBottomHeight-200, winWidth-66, 100)];
//        self.clickLinkageToStartview = clickLinkageToStartview;
        if([themeColors isEqualToString:@"default"]){
            self.clickLinkageToStartview .image = [UIImage imageNamed:@"clickLinkageToStart"];
        }else{
            self.clickLinkageToStartview .image = [UIImage imageNamed:@"clickLinkageToStartmid"];
        }
//        clickLinkageToStartview.image = [UIImage imageNamed:@"clickLinkageToStart"];
        [self.view addSubview:self.clickLinkageToStartview ];
    }else{
        self.readytolinksview.hidden = YES;
        self.clickLinkageToStartview.hidden = YES;
        [self.readytolinksview removeFromSuperview];
        [self.clickLinkageToStartview removeFromSuperview];
//        有设备链接

//        _imagesURLStrings = imagesURLStrings;
       
//        NSMutableArray *imageNames = [@[@"linkbackground",@"linkbackground"]];
        NSMutableArray *imageNames = [[NSMutableArray alloc] init];
        _imagesURLStrings = imageNames;
//        lbdataarray
        for (int i = 0; i<self.lbdataarray.count; i++) {
            [imageNames addObject:@"linkbackground"];
        }
        
        // 本地加载 --- 创建不带标题的图片轮播器
//        devicelinkScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(30, kNavHeight+10, winWidth-60, 590) shouldInfiniteLoop:NO imageNamesGroup:imageNames];
//        devicelinkScrollView.delegate = self;
//        devicelinkScrollView.pageControlStyle = SDCycleScrollViewPageContolStyleAnimated;
//        devicelinkScrollView.scrollDirection = UICollectionViewScrollDirectionVertical;
        //         --- 轮播时间间隔，默认1.0秒，可自定义
        //cycleScrollView.autoScrollTimeInterval = 4.0;
        
        devicelinkScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(30, kNavHeight+10, winWidth-60, self.height) delegate:self placeholderImage:nil];
        devicelinkScrollView.imageURLStringsGroup = _imagesURLStrings ;
        devicelinkScrollView.autoScroll = NO;
        if([themeColors isEqualToString:@"default"]){
            devicelinkScrollView.backgroundColor = [UIColor blackColor];
        }else{
            devicelinkScrollView.backgroundColor = midnightRGB;
        }
        [self.view addSubview:devicelinkScrollView];
    }
        
    }
}
- (void)bluetoothDisconnect:(NSNotification *)notification{
    
    NSDictionary *userInfo = notification.userInfo;
    NSString * uuid = [userInfo objectForKey:@"uuid"];
//
    NSLog(@"self.bluetoothddataArray :%@",self.bluetoothddataArray);
    NSLog(@"首页蓝牙断开: %@  lbdataarray:%@",userInfo,self.lbdataarray);
    for (int i = 0; i<self.lbdataarray.count; i++) {
        if(self.lbdataarray.count>0){
            if([uuid isEqualToString:[NSString stringWithFormat:@"%@",self.lbdataarray[i][@"uuid"]]]){
//                [[self.blueToothManager myDevices] removeObjectAtIndex:i];
                [self.lbdataarray removeObjectAtIndex:i];

            }
        }
        
    };
    for (int i = 0; i<self.bluetoothddataArray.count; i++) {
        if(self.bluetoothddataArray.count>0){
            if([uuid isEqualToString:[NSString stringWithFormat:@"%@",self.bluetoothddataArray[i][1][@"uuid"]]]){
//                [[self.blueToothManager myDevices] removeObjectAtIndex:i];
                [self.bluetoothddataArray removeObjectAtIndex:i];
                

            }
        }
        
    };
    
    if(self.lbdataarray.count == 0){
        
        NSLog(@"已经断开了，没有数据了");
        [devicelinkScrollView removeFromSuperview];
        [self nodata];
    }else{
       [ self adddata];
    }
//    deviceHomepagedisconnect
    [[NSNotificationCenter defaultCenter]postNotificationName:@"deviceHomepagedisconnect" object:nil userInfo:@{@"uuid":uuid}];
    NSLog(@"首页蓝牙断开 self.bluetoothddataArray :%@",self.bluetoothddataArray);
}
- (void)linkSuccess:(NSNotification *)notification{
    
    NSDictionary *userInfo = notification.userInfo;
    NSDictionary * list = [userInfo objectForKey:@"list"];
    
    NSMutableArray *dataArr = [NSMutableArray arrayWithObject:list];
    NSLog(@"首页返回来的数据：%@",list);
    NSLog(@"self.bluetoothddataArray :%@",self.bluetoothddataArray);
    NSLog(@"self.lbdataarray ::%@",self.lbdataarray);
    NSLog(@"self.dataArr ::%@",self.dataArr);
    
    NSDictionary *dict = [NSDictionary dictionaryWithDictionary:dataArr[0][1]];
    NSMutableDictionary *mudic = [NSMutableDictionary dictionaryWithDictionary:dict[@"advertisementData"]];
    NSString* uuid = [NSString stringWithFormat:@"%@",dict[@"uuid"]];
    [mudic setObject:@"1" forKey:@"kCBAdvDataislink"];

    NSDictionary *nutadict = @{@"uuid":uuid,@"advertisementData":mudic,@"name":dict[@"name"]};
    
    NSArray *datacopy = @[dataArr[0][0],nutadict];
    
//    NSString* linkuuid = [NSString stringWithFormat:@"%@",list[1][@"uuid"]];
    NSLog(@"bluetoothddataArray .... %@",self.bluetoothddataArray);
    if(self.bluetoothddataArray.count > 0){
//        NSString *dataruuid = [NSString stringWithFormat:@"%@",[self.bluetoothddataArray[0][1][@"uuid"]]];
        NSString *dataruuid = [NSString stringWithFormat:@"%@",self.bluetoothddataArray[0][1][@"uuid"]];
        if([dataruuid isEqualToString:uuid]){
            NSLog(@"vc2包含了");
        }else{
            NSLog(@"vc2没包含");
    //        [weakSelf.linkuuidarray addObject:linkuuid];
            NSLog(@"bluetoothddataArray1 %@ %@",self.bluetoothddataArray,datacopy);
            [self.bluetoothddataArray addObject:datacopy];
        }
    }else{
        NSLog(@"bluetoothddataArray2 %@ %@",self.bluetoothddataArray,datacopy);
        [self.bluetoothddataArray addObject:datacopy];
    }


//    [self.bluetoothddataArray addObject:datacopy];
    [self.lbdataarray addObject:nutadict];
    
    [self adddata];
    NSLog(@"添加后self.bluetoothddataArray :%@  self.lbdataarray:%@",self.bluetoothddataArray,self.lbdataarray);
}
//助手模式
-(void)helprjump{
//    HXHelperModeViewController
    HXHelperModeViewController*jum = [[HXHelperModeViewController alloc] init];
    
    if(!XHbluetoolUtils.beginurl){
        NSLog(@" isopen no");
        jum.isOpen = NO;
    }else{
        jum.dataaraay = self.lbdataarray[self.index];
        
        WeakSelf
        jum.disconnectDeviceBlock = ^(NSString * _Nonnull uuid) {
            NSLog(@"uuid");
            if([uuid isEqual:@"1"]){
                weakSelf.disconnectDevice = @"1";
            }
        };
        
    }
//    jum.dataaraay = self.lbdataarray[self.index];
//
//    WeakSelf
//    jum.disconnectDeviceBlock = ^(NSString * _Nonnull uuid) {
//        NSLog(@"uuid");
//        if([uuid isEqual:@"1"]){
//            weakSelf.disconnectDevice = @"1";
//        }
//    };
//
    
//    [self presentViewController:jum animated:YES completion:nil];
    jum.modalPresentationStyle = NSDateFormatterNoStyle;
    [self.navigationController pushViewController:jum animated:YES];
}
-(void)JumpLinke {
//    NSLog(@"主页没链接，跳转链接");//HXBluetoothDeviceLink
    HXBluetoothDeviceLinkViewController *JumpLinke = [[HXBluetoothDeviceLinkViewController alloc] init];
    JumpLinke.modalPresentationStyle = NSDateFormatterNoStyle;
    JumpLinke.isSkipOrNot = YES;
    if([self.disconnectDevice isEqualToString:@"1"]){
        JumpLinke.disconnectDevice = @"1";
    }
    NSLog(@"self.bluetoothddataArray :%@",self.bluetoothddataArray);

        // bluetoothddataArray 是需要处理的目标数组

        // array2 是去掉相同元素后的数组
        NSMutableArray *array2 = [NSMutableArray array];
        
        for (NSString *str in self.bluetoothddataArray) {//遍历数组1
            if (![array2 containsObject:str]) {//判断数组2中有没有该元素,如果没有就添加到数组2中,该步骤就是去掉数组中的重复元素
                [array2 addObject:str];
                NSLog(@"去重的数据%@",array2);
                self.bluetoothddataArray = [NSMutableArray arrayWithArray:array2];
            }
        }

    JumpLinke.storageArray = self.bluetoothddataArray;
//    JumpLinke.sparelinkArray = self.lbdataarray;
    NSLog(@"self.bluetoothddataArray :%@",self.bluetoothddataArray);
//    [self presentViewController:JumpLinke animated:YES completion:nil];
    [self.navigationController pushViewController:JumpLinke animated:YES];
}
-(void)solojump{

    HXSoloModeViewController*jum = [[HXSoloModeViewController alloc] init];
    jum.modalPresentationStyle = NSDateFormatterNoStyle;
    [self.navigationController pushViewController:jum animated:YES];
    
}
-(void)JumpOption{
    NSLog(@"主页跳转到设置界面");
    HXSetInterfaceViewController *vc = [[HXSetInterfaceViewController alloc] init];
    vc.modalPresentationStyle = NSDateFormatterNoStyle;
    [self.navigationController pushViewController:vc animated:YES];
    
}

-(void)detailjump:(NSNotification *)notification{
    NSDictionary *userInfo = notification.userInfo;
    NSString * index = [userInfo objectForKey:@"index"];
    HXDetailViewController *vc = [[HXDetailViewController alloc] init];
    vc.index = index.integerValue;
//    vc.model = self.model;
//    SPProduct *produce = self.goodsArray[indexPath.row];
    NSDictionary *dict = [[NSDictionary alloc] init];
    NSLog(@"self.bluetoothddataArray :%@",self.bluetoothddataArray);
    
    if(!XHbluetoolUtils.beginurl){
        NSLog(@" isopen no");
        vc.isOpen = NO;
    }else{
        
    
    if(self.index == nil){
        self.index = 0;
    }
    if(_isgai){
        dict = [NSDictionary dictionaryWithDictionary:self.bluetoothddataArray[self.index][1]];
    }else{
        dict = [NSDictionary dictionaryWithDictionary:self.lbdataarray[self.index]];
    }
//    NSDictionary *dict = [NSDictionary dictionaryWithDictionary:self.lbdataarray[self.index]];
    NSLog(@"字典：%@",dict);
    HXBluetoothConnectionDataModel *modelone = [HXBluetoothConnectionDataModel yy_modelWithDictionary:dict[@"advertisementData"]];
    vc.model =  modelone;
    
    }
    
    vc.modalPresentationStyle = NSDateFormatterNoStyle;
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)nodata{
    
    self.readytolinksview  = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"readytolinks"]];
    [self.view addSubview:self.readytolinksview ];
    [self.readytolinksview  mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(190);
        make.top.mas_equalTo(kNavHeight+120);
        make.centerX.mas_equalTo(self.view);
    }];
    
    self.clickLinkageToStartview = [[UIImageView alloc] initWithFrame:CGRectMake(33, winHeight- SafeAreaBottomHeight-200, winWidth-66, 100)];
    if([themeColors isEqualToString:@"default"]){
        self.clickLinkageToStartview.image = [UIImage imageNamed:@"clickLinkageToStart"];
    }else{
        self.clickLinkageToStartview.image = [UIImage imageNamed:@"clickLinkageToStartmid"];
    }
//        clickLinkageToStartview.image = [UIImage imageNamed:@"clickLinkageToStart"];
    [self.view addSubview:self.clickLinkageToStartview];
}
//textViewname
-(void)textViewname:(NSNotification *)notification{
    NSDictionary *userInfo = notification.userInfo;
    NSString * textViewname = [userInfo objectForKey:@"textViewname"];
    NSDictionary *dict = [NSDictionary dictionaryWithDictionary:self.lbdataarray[self.index]];
//    NSLog(@"字典：%@",dict);
    HXBluetoothConnectionDataModel *modelone = [HXBluetoothConnectionDataModel yy_modelWithDictionary:dict[@"advertisementData"]];
    NSLog(@"修改前的数据：%@",self.lbdataarray[self.index]);
    NSLog(@"修改的名字：%@",textViewname);
//    {
//        advertisementData =     {
//            kCBAdvDataEquipmenttime = "";
//            kCBAdvDataIsConnectable = 1;
//            kCBAdvDataLocalName = hellword;
//            kCBAdvDataManufacturerData = "";
//            kCBAdvDataRxPrimaryPHY = 1;
//            kCBAdvDataRxSecondaryPHY = 0;
//            kCBAdvDataServiceUUIDs = "6E400001-B5A3-F393-E0A9-E50E24DCCA9E";
//            kCBAdvDataTimestamp = "";
//            kCBAdvDataislink = 1;
//        };
//        name = hellword;
//        uuid = "E4DFF8B3-B614-F57B-C8D9-2ECFC2495FC5";
//    }
    NSDictionary *dic1 = @{@"kCBAdvDataEquipmenttime":modelone.kCBAdvDataEquipmenttime,@"kCBAdvDataLocalName":textViewname,
                           @"kCBAdvDataManufacturerData":modelone.kCBAdvDataManufacturerData,
                           @"kCBAdvDataServiceUUIDs":modelone.kCBAdvDataServiceUUIDs,
                           @"kCBAdvDataTimestamp":modelone.kCBAdvDataTimestamp,
                           @"kCBAdvDataislink":@"1"
    };
    NSLog(@"dic1 :%@",dic1);

    NSMutableDictionary * mdic = [[NSMutableDictionary alloc] init];
//    NSMutableDictionary * dict2 = @{@"name":modelone.name,@"uuid":modelone.uuid};
//    [dict2 addEntriesFromDictionary:dic1];
    [mdic setObject:dic1 forKey:@"advertisementData"];
    [mdic setObject:dict[@"name"] forKey:@"name"];
    [mdic setObject:dict[@"uuid"] forKey:@"uuid"];
    NSString *name ;
    NSString *uuid ;
    if(modelone.name == nil){
        name = @"";
    }
    if(modelone.uuid == nil){
        name = @"";
    }
//    [mdic setObject:modelone.name forKey:@"name"];
//    [mdic setObject:modelone.uuid forKey:@"uuid"];
    NSLog(@"dict2 :%@",mdic);
    
//    self.bluetoothddataArray = [self.bluetoothddataArray[0],mdic];
    NSMutableArray *nutarray = [[NSMutableArray alloc] init];
    NSMutableArray *dataArray = [[NSMutableArray alloc] init];
    dataArray = self.bluetoothddataArray[self.index][0];
//    [nutarray addObject:self.bluetoothddataArray[self.index][0]];
//    [nutarray addObject:mdic];
    NSLog(@"nutarray :%@",nutarray);
   
//    [self.deviceList addObject:@[peripheral,advertisementData,macString]];
    
    [nutarray addObject:@[dataArray,mdic]];
    self.bluetoothddataArray = nutarray;
    self.isgai = YES;
    NSLog(@"bluetoothddataArray :%@   \n nutarray:%@",self.bluetoothddataArray ,nutarray);
  
}

- (void)huoqushijian{
//    //    获取最后的时间
//    Byte send[] = {0x58,0x57,0x03,0x0B,0x00,0x00,0x00,0x01};
//    NSData *sendData = [NSData dataWithBytes:&send length:sizeof(send)];
//    [self.blueToothManager writeData:sendData];
//    
//    NSLog(@"blueToothManager: %@",self.blueToothManager);
//    //    链接
////    self.blueToothManager.datastrBlock = ^(NSString * _Nonnull datastr) {
////        NSLog(@"获取最后的时间： %@",datastr);
////    };
//    self.blueToothManager.datalasttimeBlock = ^(NSString * _Nonnull lasttime) {
//        NSLog(@"获取最后的时间： %@",lasttime);
//        NSArray *Arr = [NSArray array];
//        Arr = [lasttime componentsSeparatedByString:@"0x585703"];
//        NSLog(@"获取最后的时间：%@",Arr);
//        NSString *results2 = [Arr[1] substringToIndex:8];
//        NSString *results3 = [Arr[1] substringToIndex:8];
//        
//        NSString *time = [results2 substringWithRange:NSMakeRange(4, 2)];
//        NSString *minute = [results2 substringWithRange:NSMakeRange(6, 2)];
//        NSLog(@"\n时:%@\n分:%@",time,minute);
//    };
}
-(void)tutoriajump{
    
    HXTutorialViewController *vc = [[HXTutorialViewController alloc] init];
    vc.modalPresentationStyle = NSDateFormatterNoStyle;
    [self.navigationController pushViewController:vc animated:YES];
}
#pragma mark - SDCycleScrollViewDelegate

- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index
{
    NSLog(@"---点击了第%ld张图片", (long)index);

    
}



 
// 滚动到第几张图回调
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didScrollToIndex:(NSInteger)index
{
    NSLog(@">>>>>> 滚动到第%ld张图", (long)index);
    self.index = index;
}
 
 






// 不需要自定义轮播cell的请忽略下面的代理方法

// 如果要实现自定义cell的轮播图，必须先实现customCollectionViewCellClassForCycleScrollView:和setupCustomCell:forIndex:代理方法

- (Class)customCollectionViewCellClassForCycleScrollView:(SDCycleScrollView *)view
{
    if (view != devicelinkScrollView) {
        return nil;
    }
    return [HXbluetoothLinkStyleCell class];
}

- (void)setupCustomCell:(UICollectionViewCell *)cell forIndex:(NSInteger)index cycleScrollView:(SDCycleScrollView *)view
{
    // 情景二：采用网络图片实现
    
//    linkbackground
    HXbluetoothLinkStyleCell *myCell = (HXbluetoothLinkStyleCell *)cell;
    
//    myCell.model = self.model;
//    self.lbdataarray[self.index];
    NSLog(@"index :%ld",index);
    NSLog(@"%@",self.lbdataarray);
    
    if(!XHbluetoolUtils.beginurl){
        
        
//        NSDictionary *dict = [NSDictionary dictionaryWithDictionary:self.lbdataarray[index]];
//        NSLog(@"字典：%@",dict);
        NSDictionary *dict =@{@"isopen":@"NO"};
        self.model = [HXBluetoothConnectionDataModel yy_modelWithDictionary:dict];
    
        myCell.model = self.model;
        
        
    //    NSString *name = [NSString stringWithFormat:@"%02ld.jpg", index + 1];
        NSString *name = [NSString stringWithFormat:@"linkbackground.png"];
        UIImage *img = [UIImage imageNamed:name];
        NSLog(@"图片的name:%@",name);
        if(!img) {
            NSLog(@"name :%@", name);
        }
//        myCell.lbdataarray = self.lbdataarray[index];
        myCell.imgView.image = img;
        myCell.dissindex = index + 1;
//        myCell.isopen = NO;
        
    }else{
        
   
    
    
    NSDictionary *dict = [NSDictionary dictionaryWithDictionary:self.lbdataarray[index]];
    NSLog(@"字典：%@",dict);
    self.model = [HXBluetoothConnectionDataModel yy_modelWithDictionary:dict[@"advertisementData"]];
    myCell.model = self.model;
    
    
//    NSString *name = [NSString stringWithFormat:@"%02ld.jpg", index + 1];
    NSString *name = [NSString stringWithFormat:@"linkbackground.png"];
    UIImage *img = [UIImage imageNamed:name];
    NSLog(@"图片的name:%@",name);
    if(!img) {
        NSLog(@"name :%@", name);
    }
//    [imgView setImage:img];
//    [myCell.imgView setImage:img];
    myCell.lbdataarray = self.lbdataarray[index];
    
    myCell.imgView.image = img;
    myCell.dissindex = index + 1;
    }
    
    
}
-(void)dealloc{
    
//    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
